import { createRouter, createWebHistory, useRouter } from 'vue-router'
import { toast } from '@/util/toast';
import { checkLogin } from "../util/checkLogin";

const loadComponent = (path) => () => import(`../views/${path}.vue`);
const routes = [
  {
    path: '/login',
    name: 'login',
    component: loadComponent('LoginForm/LoginForm'),
  },
  {
    path: '/register',
    name: 'register',
    component: loadComponent('RegisterForm/RegisterForm'),
  },
  {
    path: '/',
    name: 'home',
    redirect: '/login',
    component: loadComponent('LoginForm/LoginForm'),
  },
  {
    path: '/home',
    name: 'home1',
    component: loadComponent('HomeView/HomeView'),
    meta: {
      keepAlive: true //此页面需要缓存
    }
  },
  {
    path: '/detail',
    name: 'detail',
    component: loadComponent('DetailView/DetailView'),
    meta: {
      keepAlive: false //此页面需要缓存
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: loadComponent('CartView/CartView'),
  },
  {
    path: '/mine',
    name: 'mine',
    component: loadComponent('Mineview/MineView'),
  },
  {
    path: '/catagory',
    name: 'catagory',
    component: loadComponent('Catogory/Catogory'),
  },
  {
    path: '/add_address',
    name: 'add_address',
    component: loadComponent('AddressAdd/AddressAdd'),
  },
  {
    path: '/addresslist',
    name: 'addresslist',
    component: loadComponent('AddressList/AddressList'),
  },
  {
    path: '/search',
    name: 'search',
    component: loadComponent('SearchView/SearchView'),
    meta:{
      keepAlive:true
    }
  },
  {
    path: '/myorder',
    name: 'myorder',
    component: loadComponent('MyOrderView/OrderView'),
  },
  {
    path: '/order',
    name: 'order',
    component: loadComponent('OrderView/order')
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('@/views/TestView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior (to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    if(savedPosition) {
      return savedPosition
    }
    else {
      return {top:0}
    }
  }
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 在进入路由前判断用户是否已登录
  const isLogin = localStorage.getItem('token') // token为登录凭证
  if(['/home','/detail','/search','/catagory','/register', '/login'].includes(to.path)) {
    next()
    return
  }
  if (!isLogin && to.path !== '/login') {
    toast('fail', '请先登录',500)
    next('/login') // 若未登录则跳转到登录页
  } else {
    next() // 放行
  }
})

export default router
